<!-- 瀑布流布局 -->
<template>
  <view class="container scroll">
		<view
		  :id="`cont_${index + 1}`"
		  class="cont-box"
		  :style="{ width: widthCalc, 'margin-left': index === 0 ? 0 : marginCalc }"
		  v-for="(numVal, index) in flowData.column"
		  :key="numVal"
		>
		  <view class="item-box" v-for="(item, j) in flowData[`column_${index + 1}`]" :key="j"  @click="tiao(item)">
			<image class="img-tip" :src="item.cover" mode="widthFix" lazy-load @load="imgLoad(item)" @error="imgError(item)" />
			<view class="tit-tip multi-line-omit">{{ item.resourceName }}</view>
			<view class="desc-tip multi-line-omit">
			<text>{{ item.press }}</text>
			<view>
				<view  @click.stop="like(item)" v-if='item.sfLike == 1' style="width:100rpx;display:flex;flex-wrap:wrap;justify-content: flex-end;">
					<uv-icon name="heart-fill" color="red" style="width:40rpx;height:40rpx;"></uv-icon>
					<text>{{item.likeCount}}</text>
				</view>
				<view  @click.stop="like(item)" v-else style="width:100rpx;display:flex;flex-wrap:wrap;justify-content: flex-end;">
					<uv-icon name="heart" style="width:20rpx;height:20rpx;"></uv-icon>
					<text>{{item.likeCount}}</text>
				</view>
			</view>
			</view>
		  </view>
		</view>
  </view>
</template>
 
<script setup>
import { reactive, computed, getCurrentInstance, onMounted, defineProps,watch,defineEmits } from "vue";
 import useGetGlobalProperties from '@/util/useGlobal.js'
 const emit = defineEmits(['submit'])
 const props = defineProps({
   listdata: {
     type: Array,
     required: true
   }
 });
const _this = getCurrentInstance();
const urls = useGetGlobalProperties().$https;
const flowData = reactive({
  list: [], // 数据值
  column: 2, // 瀑布列数
  columnSpace: 2 // 瀑布列宽间距
});

watch(()=>props.listdata,
  (newVal, oldVal) => {
    flowData.list = newVal
	console.log(flowData.list)
	initValue(0)
  },{deep:true,immediate:true},
)

/* 初始化每一列的数据 */
for (let i = 1; i <= flowData.column; i++) {
  flowData[`column_${i}`] = [];
}

/* 生命周期函数-实例被挂载后调用 */
onMounted(() => {
  initValue(0);
});
/* 计算列宽 */
const widthCalc = computed(() => {
  return `${100 / flowData.column - flowData.columnSpace}%`;
});
/* 计算 margin 外边距 */
const marginCalc = computed(() => {
  const columnWidth = 100 / flowData.column - flowData.columnSpace;
  return `${(100 - columnWidth.toFixed(5) * flowData.column) / (flowData.column - 1)}%`;
});
/* 获取最小值的对象 */
const getMinObj = (a, s) => {
  let m = a[0][s];
  let mo = a[0];
  for (let i = a.length - 1; i >= 0; i--) {
    if (a[i][s] < m) m = a[i][s];
  }
  mo = a.filter(i => i[s] === m);
  return mo[0];
};
/* 计算每列的高度 */
function getMinColumnHeight() {
  return new Promise(resolve => {
    const heightArr = [];
    for (let i = 1; i <= flowData.column; i++) {
      uni
        .createSelectorQuery()
        .in(_this)
        .select(`#cont_${i}`)
        .boundingClientRect(res => {
          heightArr.push({ column: i, height: res.height });
        })
        .exec(() => {
          if (flowData.column <= heightArr.length) {
            resolve(getMinObj(heightArr, "height"));
          }
        });
    }
  });
}
/* 初始化瀑布流数据 */
async function initValue(i) {
	if(i == 0){
		for (let i = 1; i <= flowData.column; i++) {
		  flowData[`column_${i}`] = [];
		}
	}
  if (i >= flowData.list.length) return false;
  const minHeightRes = await getMinColumnHeight();
  flowData[`column_${minHeightRes.column}`].push({
    ...flowData.list[i],
    index: i
  });
}
/* 图片加载完成 */
function imgLoad(item) {
  const i = item.index;
  initValue(i + 1); // 加载下一条数据
}
/* 图片加载失败 */
function imgError(item) {
  const i = item.index;
  initValue(i + 1); // 加载下一条数据
}
// 上拉加载
const more = ()=>{
	console.log('上拉了')
}
const tiao = (e) => {
	console.log(e.dataTypId,'=====')
	// let urls = '';
	if(e.dataTypeId=='1719628549662441474'){
		uni.navigateTo({
			url:'/pages/index/audioDetails/audioDetails?id=' + e.resourceId
		})
	} else if(e.dataTypeId=='1719628572391374849') {
		uni.navigateTo({
			url:'/pages/index/videoDetails/videoDetails?id=' + e.resourceId
		})
	}
	else if(e.dataTypeId=='1719628593258037250') {
		uni.navigateTo({
			url:'/pages/index/journalDetails/journalDetails?id=' + e.resourceName
		})
	}
	else{
		uni.navigateTo({
			url:'/pages/index/bookDetail/bookDetail?id='+e.resourceId
		})
	}
}
// 点赞/取消点赞
const goLike = (item,openId,sfLike)=>{
	uni.request({
		url: urls + (sfLike == 1 ?'/ruralLibrary/resource/cancelLike':'/ruralLibrary/resource/like'),
		method: 'GET',
		data: {
			openId,
			id:item.resourceId,
		},
		success: (res) => {
			console.log('start', res.data)
			uni.showToast({
				title: '操作成功!',
				icon: 'success',
				duration: 1500,
				mask: false
			});
			// emit('submit')
			item.sfLike = item.sfLike == 1 ? 0 : 1
			item.sfLike == 1 ? item.likeCount ++ : item.likeCount --
		}
	})
}
const like = (item)=>{
	// 判断是否登录
	let user = uni.getStorageSync('userInfo');
	if(user){
		goLike(item,user.openId,item.sfLike)
	}else{
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success: res => {
				console.log(res, '登录成功')
				let code = res.code;
				console.log("code=" + res.code);
				uni.request({
					url:  'https://wechat.shuzinongyue.com:8922/userInfo/getOpenId/' + code,
					method: 'GET',
					success: (res) => {
						if (res.data.data) {
							uni.setStorageSync('userInfo', res.data.data);
							goLike(item,res.data.data.openId,item.sfLike)							
						} else {
							uni.showToast({
								title: '请登录后进行操作',
								icon: 'success',
								duration: 1000,
								mask: false
							});
						}
					}
				})
			}
		})
	}
}
</script>
 
<style lang="scss" scoped>
.container {
  padding: 20rpx;
  .cont-box {
    $borderRadius: 12rpx;
    float: left;
    .item-box {
      width: 100%;
      padding-bottom: 20rpx;
      margin-bottom: 30rpx;
      border-radius: $borderRadius;
      box-shadow: 0rpx 3rpx 6rpx rgba(0, 46, 37, 0.08);
      .img-tip {
        width: 100%;
        border-radius: $borderRadius $borderRadius 0 0;
      }
      .tit-tip {
        text-align: justify;
        font-size: 30rpx;
        padding: 10rpx 20rpx 0;
        font-weight: 900;
      }
      .desc-tip {
        text-align: justify;
        font-size: 26rpx;
        padding: 5rpx 20rpx 0;
        margin-top: 10rpx;
		display:flex;
		justify-content: space-between;
      }
    }
  }
}
/* 多行省略 */
.multi-line-omit {
  word-break: break-all; // 允许单词内自动换行，如果一个单词很长的话
  text-overflow: ellipsis; // 溢出用省略号显示
  overflow: hidden; // 超出的文本隐藏
  display: -webkit-box; // 作为弹性伸缩盒子模型显示
  -webkit-line-clamp: 2; // 显示的行
  -webkit-box-orient: vertical; // 设置伸缩盒子的子元素排列方式--从上到下垂直排列
}
/* 单行省略 */
.one-line-omit {
  width: 100%; // 宽度100%：1vw等于视口宽度的1%；1vh等于视口高度的1%
  white-space: nowrap; // 溢出不换行
  overflow: hidden; // 超出的文本隐藏
  text-overflow: ellipsis; // 溢出用省略号显示
}
</style>